<template>
  <div class="putProducts">
    <el-form ref="ruleFormRef" :model="initialData" :rules="rules" label-width="auto" class="demo-ruleForm"
      :size="formSize" status-icon>
      <el-row>
        <el-col :span="12">
          <div class="grid-content ep-bg-purple">
            <el-form-item label="商品图片">
              <el-upload v-model:file-list="fileList" action="#" list-type="picture-card" :auto-upload="false">
                <el-icon>
                  <Plus />
                </el-icon>
  
                <template #file="{ file }">
                  <div>
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                        <el-icon><zoom-in /></el-icon>
                      </span>
                      <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
  
              <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
            </el-form-item>
            <el-form-item label="商品标题/名称" prop="productTitle">
              <el-input v-model="initialData.productTitle" />
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="initialData.price" />
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content ep-bg-purple-light">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="initialData.brand" />
            </el-form-item>
            <el-form-item label="上市时节" prop="marketSeason">
              <el-input v-model="initialData.marketSeason" placeholder="例：2025年春季" />
            </el-form-item>
  
            <el-form-item label="运动鞋科技" prop="sst">
              <el-checkbox-group v-model="initialData.sst">
                <el-checkbox value="缓震胶" name="sst"> 缓震胶 </el-checkbox>
                <el-checkbox value="扭转系统" name="sst">
                  扭转系统
                </el-checkbox>
                <el-checkbox value="易弯折功能" name="sst">
                  易弯折功能
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
  
            <el-form-item label="鞋底材质" prop="soleMaterial">
              <el-radio-group v-model="initialData.soleMaterial">
                <el-radio value="橡胶">橡胶</el-radio>
              </el-radio-group>
            </el-form-item>
  
            <el-form-item label="功能特性" prop="functionality">
              <el-checkbox-group v-model="initialData.functionality">
                <el-checkbox value="耐磨" name="functionality">
                  耐磨
                </el-checkbox>
                <el-checkbox value="包裹性" name="functionality">
                  包裹性
                </el-checkbox>
                <el-checkbox value="减震" name="functionality">
                  减震
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
  
            <el-form-item label="鞋帮高度" prop="upperHeight">
              <el-radio-group v-model="initialData.upperHeight">
                <el-radio value="高帮">高帮</el-radio>
                <el-radio value="低帮">低帮</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="适用人群" prop="applicableCrowd">
              <el-radio-group v-model="initialData.applicableCrowd">
                <el-radio value="通用">通用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="鞋面材质" prop="upperMaterial">
              <el-radio-group v-model="initialData.upperMaterial">
                <el-radio value="网布">网布</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="运动系列" prop="sportsSeries">
              <el-radio-group v-model="initialData.sportsSeries">
                <el-radio value="篮球比赛鞋">篮球比赛鞋</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="适用场地" prop="applicableVenues">
              <el-radio-group v-model="initialData.applicableVenues">
                <el-radio value="室内地板">室内地板</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="制作工艺" prop="craftsmanship">
              <el-radio-group v-model="initialData.craftsmanship">
                <el-radio value="胶粘">胶粘</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          修改
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, PropType } from "vue";
import { updateProduct, uploadaddProduct } from "../api/products";
import type {
  ComponentSize,
  FormInstance,
  FormRules,
  UploadFile,
} from "element-plus";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { productsStore } from "../../store/user";
import { useRouter } from "vue-router";
import { Products, rules, arrayOnString } from "../ts/products";

const router = useRouter();
const products = productsStore();

const fileList = ref([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);

const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();



const props = defineProps({
  initialData: {
    type: Object as PropType<Products>,
    required: true
  }
})

// 手动加载图片
const lodingImg = () => {

  props.initialData.icon.forEach(url => {

    const newFile = {
      uid: Date.now() + Math.random().toString(36).substr(2), // 生成唯一ID
      name: url,
      status: 'success',
      url: url,
      size: 0,
      type: 'image/jpeg',
    };

    fileList.value = [...fileList.value, newFile];
  })
}
lodingImg();

const handleRemove = (file: UploadFile) => {
  props.initialData.icon = props.initialData.icon.filter(url => url !== file.url)
  fileList.value = fileList.value.filter(f => f.uid !== file.uid);
};

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogVisible.value = true;
};



const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const formData = new FormData();
      const hasFiles = fileList.value.some(file => file.raw);  // 检查是否有有效文件

      fileList.value.forEach((file) => {
        formData.append("file", file.raw);

      });


      // 图片上传oss  如果有有效文件就上传图片
      if (hasFiles) {
        uploadaddProduct(formData).then((ossRes) => {
          if (ossRes.success) {

            ossRes.data.urls.forEach((url) => {
              props.initialData.icon.push(url);
            })

            updateProduct(arrayOnString(props.initialData)).then((res) => {
              if (res.success) {
                ElMessage({
                  message: "修改成功",
                  type: "success",
                });
              }
            });

            // 上传成功后可以清空文件列表
            fileList.value = [];
          }
        });
      } else {
        updateProduct(arrayOnString(props.initialData)).then((res) => {
          if (res.success) {
            ElMessage({
              message: "修改成功",
              type: "success",
            });
          }
        });
      }

    } else {
      ElMessage.error("注意红星必填项");
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  fileList.value = [];
  lodingImg();
  formEl.resetFields();
};
</script>

<style lang="less" scoped>
.putProducts {
  // overflow:auto;
  overflow: visible;
}
</style>
